<?php

namespace app\common\model;

use think\Model;

class Goods extends Model
{
    protected $name = 'goods';
    
    // 自动写入时间戳
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    
    // 追加属性
    protected $append = [
        'status_text',
        'min_price',    // 最低价格
        'max_price'     // 最高价格
    ];

    // 图片JSON自动转换
    protected function getImagesAttr($value)
    {
        return $value ? explode(',',$value) : [];
    }

    protected function setImagesAttr($value)
    {
        return $value ? implode(',',$value) : '';
    }
    
    public function getStatusList()
    {
        return ['0' => '下架', '1' => '上架'];
    }
    
    public function getStatusTextAttr($value, $data)
    {
        $status = $this->getStatusList();
        return isset($status[$data['status']]) ? $status[$data['status']] : '';
    }

    // 获取最低价格
    public function getMinPriceAttr($value, $data)
    {
        return $this->specs()->min('price') ?: '0.00';
    }

    // 获取最高价格
    public function getMaxPriceAttr($value, $data)
    {
        return $this->specs()->max('price') ?: '0.00';
    }

    // 规格关联
    public function specs()
    {
        return $this->hasMany('GoodsSpec', 'goods_id');
    }

    // 获取商品总库存
    public function getTotalStock()
    {
        return $this->specs()->sum('stock') ?: 0;
    }

    // 获取商品总销量
    public function getTotalSales()
    {
        return $this->specs()->sum('sales') ?: 0;
    }

    public function category()
    {
        return $this->belongsTo('GoodsCategory', 'category_id', 'id');
    }
    public function spec()
    {
        return $this->hasMany('GoodsSpec', 'goods_id');
    }
}